import type React from "react"
import { useEffect, useRef, type ReactNode } from "react"
import { useLocation, useNavigate } from "react-router"
import useRequest from "../hooks/useRequest"
import { checkIsLoggedIn } from "../configs/api"
import titles from "../configs/titles"

interface IRouterEnterProps {
  children: ReactNode
}

/**
 * 路由前置守卫
 */
const RouterEnter: React.FC<IRouterEnterProps> = ({ children }) => {
  // 用于跳转路由
  const navigate = useNavigate()
  // 用于获取路由信息
  const location = useLocation()

  // 从本地存储中拿到登录标识
  const isLoggedIn = useRef(localStorage.isLoggedIn)

  // 判断是否需要登录的接口
  const hasLoggedInApi = useRequest(checkIsLoggedIn)

  useEffect(() => {
    if (!isLoggedIn.current) hasLoggedInApi()
      .then((res) => {
        if (res) {
          // 如果是登录状态 正常运行 并且在本地补上登录标识
          localStorage.isLoggedIn = '1'
        } else {
          // 如果不是登录的状态 跳转到登录页面并且携带 query参数、state状态信息和pathname路径
          navigate('/login', {
            state: {
              search: window.location.search,
              state: location.state,
              pathname: location.pathname
            }
          })
        }
      })
  }, [hasLoggedInApi, navigate, isLoggedIn, location])

  // 自动设置配置好的标题
  useEffect(() => {
    if (location.pathname)
      document.title = titles.get(location.pathname) || ''
  }, [location])

  // 不管是否登录都允许访问
  return children
}

export default RouterEnter
